<template>
  <div class="searchable-row">
    <Checkbox :indeterminate="indeterminate" :value="isSelectAllColumns"
      @click.prevent.native="handleSelectAllColumns">全选</Checkbox>
    <Divider dashed />
    <CheckboxGroup v-model="selectColumns" @on-change="onSelectColumnsChange">
      <template v-for="(column, index) in table.displayColumns">
        <Checkbox :label="column.name" :key="index" />
      </template>
    </CheckboxGroup>
  </div>
</template>

<script>
export default {
  props: ['table'],
  data() {
    return {
      /** 原始表格数据项备份 */
      sourceColumns: [],
      // 处理自定义表格显示字段
      selectColumns: [],
      /** boolean，表示自定义字段复选框全选状态 */
      indeterminate: false,
      /** boolean，表示自定义字段复选框是否全选 */
      isSelectAllColumns: true
    };
  },
  mounted() {
    if (this.selectColumns.length === 0 && this.table.columns.length !== 1) {
      // 设置初始选中全部字段
      this._selectAllColumns();
    }
  },
  methods: {
    /** 选中全部字段 */
    _selectAllColumns() {
      this.selectColumns = [];
      this.table.displayColumns.forEach(item => {
        this.selectColumns.push(item.name);
      });
    },

    /** 处理全选复选框点击 */
    handleSelectAllColumns() {
      if (this.indeterminate) {
        this.isSelectAllColumns = false;
      } else {
        this.isSelectAllColumns = !this.isSelectAllColumns;
      }
      this.indeterminate = false;

      if (this.isSelectAllColumns) {
        this._selectAllColumns();
      } else {
        this.selectColumns = [];
      }

      this.handleSaveCustomColumns();
    },

    /** 处理字段复选框点击 */
    onSelectColumnsChange(data) {
      if (data.length === this.table.displayColumns.length) {
        this.indeterminate = false;
        this.isSelectAllColumns = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.isSelectAllColumns = false;
      } else {
        this.indeterminate = false;
        this.isSelectAllColumns = false;
      }

      this.handleSaveCustomColumns();
    },

    /** 保存表格字段显示状态 */
    handleSaveCustomColumns() {
      if (this.sourceColumns.length === 0) {
        this.sourceColumns = this.table.columns;
      }
      this.table.columns = [];
      this.sourceColumns.forEach(column => {
        if (column.type == 'selection') {
          this.table.columns.push(column);
        } else if (this.selectColumns.indexOf(column.title) > -1) {
          this.table.columns.push(column);
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.searchable-row {
  padding: 8px !important;
  .ivu-divider {
    margin: 6px 0;
  }
}
</style>
